package com.canyou.aspect;

import com.canyou.datascope.DataScope;
import com.canyou.system.service.UserService;
import com.canyou.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 数据权限参数注入
 *
 * @author fy
 * @date 20/02/21 14:54
 */
@Aspect
@Component
@Slf4j
public class DataScopeAspect {

    @Autowired
    private UserService userService;

    /**
     * mapper切入点
     */
    @Pointcut("execution(* com.canyou.*.mapper.*Mapper.*(.., com.canyou.datascope.DataScope, ..))")
    public void mapperPointCut() {
    }

    @Before("mapperPointCut()")
    public void beforeMethod(JoinPoint joinPoint) {
        DataScope dataScope;
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            for (Object arg : args) {
                if (arg instanceof DataScope) {
                    dataScope = (DataScope) arg;
                    // 如果是admin, 不做数据过滤
                    if ("admin".equalsIgnoreCase(userService.getCurrentUsername())) {
                        dataScope.setScopeIds(null);
                        break;
                    }

                    // 如果用户自己构建了完整的scope
                    if (StringUtils.isNotBlank(dataScope.getScopeName()) && dataScope.getScopeIds() != null) {
                        return;
                    }
                    DataScope newScope;
                    // 用户自定义数据权限的类型
                    if (dataScope.getDataPermEnum() != null) {
                        newScope = userService.getDataScope(userService.getCurrentUserId(), dataScope.getDataPermEnum());
                    } else {
                        // 使用用户角色中的数据权限类型
                        newScope = userService.getCurrentUserDataScope();
                    }
                    // 不需要数据权限过滤
                    if (newScope == null) {
                        dataScope.setScopeIds(null);
                        break;
                    }
                    // 将计算出的scopeName和scopeIds进行选择填充
                    if (StringUtils.isBlank(dataScope.getScopeName())) {
                        dataScope.setScopeName(newScope.getScopeName());
                    }
                    if (dataScope.getScopeIds() == null) {
                        dataScope.setScopeIds(newScope.getScopeIds());
                    }
                    break;
                }
            }
        }
    }

}
